<?php 
namespace App\library;

class UtilFunction { 
	/*时间文字*/
	static function word_time($time) {
        $time = is_string($time)?strtotime($time):intval($time);
        $int = $time;
        $str = '';
        if ($int <= 2){
            $str = sprintf('瞬间', $int);
        }elseif ($int < 60){
            $str = sprintf('%d秒', $int);
        }elseif ($int < 3600){
            $str = sprintf('%d分钟', floor($int / 60));
        }elseif ($int < 86400){
            $str = sprintf('%d小时', floor($int / 3600));
        }elseif ($int < 2592000){
            $str = sprintf('%d天', floor($int / 86400));
        }else{
            $str = date('Y-m-d H:i:s', $time);
        }
        return $str;
    }

    /*经过时间转文字*/
	static function word_pass_time($time) {
        $time = (int) substr($time, 0, 10);
        $int = time() - $time;
        $str = '';
        if ($int <= 2){
            $str = sprintf('刚刚', $int);
        }elseif ($int < 60){
            $str = sprintf('%d秒前', $int);
        }elseif ($int < 3600){
            $str = sprintf('%d分钟前', floor($int / 60));
        }elseif ($int < 86400){
            $str = sprintf('%d小时前', floor($int / 3600));
        }elseif ($int < 2592000){
            $str = sprintf('%d天前', floor($int / 86400));
        }else{
            $str = date('Y-m-d H:i:s', $time);
        }
        return $str;
    }

    /*将出生年月转为年龄*/
    static function date_age($birth){
        $age = strtotime($birth); 
        if($age === false){ 
            return false; 
        } 
        list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
        $now = strtotime("now"); 
        list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); 
        $age = $y2 - $y1; 
        if((int)($m2.$d2) < (int)($m1.$d1)) 
            $age -= 1; 

        return $age; 
    }

    /*根据生日 判断星座*/
    static function get_constellation($birth){
        $age = strtotime($birth);
        if($age === false){
            return false;
        }
        list($year,$month,$day) = explode("-",date("Y-m-d",$age));
        $day   = intval($day);
        $month = intval($month);
        if ($month < 1 || $month > 12 || $day < 1 || $day > 31) return false;
        $signs = array(
            array('20'=>'宝瓶座'),
            array('19'=>'双鱼座'),
            array('21'=>'白羊座'),
            array('20'=>'金牛座'),
            array('21'=>'双子座'),
            array('22'=>'巨蟹座'),
            array('23'=>'狮子座'),
            array('23'=>'处女座'),
            array('23'=>'天秤座'),
            array('24'=>'天蝎座'),
            array('22'=>'射手座'),
            array('22'=>'摩羯座')
        );
        list($start, $name) = each($signs[$month-1]);
        if ($day < $start)
            list($start, $name) = each($signs[($month-2 < 0) ? 11 : $month-2]);
        return $name;
    }

    /**
     * 获取真实的Ip地址
     * @return String
     */
    public static function get_ip()
    {
        if (isset ($_SERVER ['HTTP_QVIA'])) {
            $ip = qvia2ip($_SERVER ['HTTP_QVIA']);
            if ($ip) {
                return $ip;
            }
        }
        if (isset ($_SERVER ['HTTP_CLIENT_IP']) and !empty ($_SERVER ['HTTP_CLIENT_IP'])) {
            return CCCommonUtil::filterIp($_SERVER ['HTTP_CLIENT_IP']);
        }
        if (isset ($_SERVER ['HTTP_X_FORWARDED_FOR']) and !empty ($_SERVER ['HTTP_X_FORWARDED_FOR'])) {
            $ip = strtok($_SERVER ['HTTP_X_FORWARDED_FOR'], ',');
            return CCCommonUtil::filterIp($ip);
        }
        if (isset ($_SERVER ['HTTP_PROXY_USER']) and !empty ($_SERVER ['HTTP_PROXY_USER'])) {
            return CCCommonUtil::filterIp($_SERVER ['HTTP_PROXY_USER']);
        }
        if (isset ($_SERVER ['REMOTE_ADDR']) and !empty ($_SERVER ['REMOTE_ADDR'])) {
            return CCCommonUtil::filterIp($_SERVER ['REMOTE_ADDR']);
        } else {
            return "0.0.0.0";
        }
    }

    /*获取当前是第几周*/
    public static function current_week($date_of_firstday='2006-8-28'){ 
        //开学第一天的时间戳 
        $year = substr($date_of_firstday,0,4); 
        $month = substr($date_of_firstday,5,1); 
        $day = substr($date_of_firstday,7,2); 
        $timestamp_of_first_day = mktime(0,0,0,$month,$day,$year); 
        //今天的时间戳 
        $month = date('n'); //获取月 n 
        $day = date('d');   //获取日 d 
        $year = date('Y');  //获取年 Y 
        $timestamp_of_current_day = mktime(0,0,0,$month,$day,$year); 
        $cha = ($timestamp_of_current_day - $timestamp_of_first_day)/60/60/24; 
        $zhou = (int)(($cha)/7 +1); 
        return $zhou; 
    }

    /**
     * 计算活跃时间
     */
    public static  function get_active_time($interval){
        if($interval<60){
            $return_data = "刚刚";
        }elseif($interval<(60*60)){
            $interval = floor($interval/60);
            $return_data = $interval."分钟前";
        }elseif($interval<(60*60*24)){
            $interval = floor($interval/60/60);
            $return_data = $interval."小时前";
        }else{
            $interval = floor($interval/60/60/24);
            $return_data = $interval."天前";
        }
        return $return_data;
    }

    /**
     * 订单自动取消剩余时间
     */
    public static function get_order_plus_time($order_create_time){
        app()->configure('base');
        $order_cancel_time = config('base.order_cancel_time');
        $plus_second = $order_cancel_time+$order_create_time-time();
        if($plus_second>=86400){
            $result = floor($plus_second/86400)."天";
        }elseif($plus_second>=3600){
            $result = floor($plus_second/3600)."小时";
        }elseif($plus_second>=60){
            $result = floor($plus_second/60)."分钟";
        }elseif($plus_second>0){
            $result = $plus_second."秒";
        }else{
            $result = 0;
        }
        return $result;
    }

    /**
     * @desc 根据两点间的经纬度计算距离
     * 返回单位为米
     * @param float $lat 纬度值
     * @param float $lng 经度值
     */
    public static  function get_distance($lat1, $lng1, $lat2, $lng2)
    {

        $earthRadius = 6367000; //approximate radius of earth in meters

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        $distance =  round($calculatedDistance);

        if($distance>1000){
            $distance = round($distance/1000,1)."km";
        }else{
            $distance = $distance."m";
        }
        return $distance;
    }

    public static  function get_distance_true($lat1, $lng1, $lat2, $lng2)
    {

        $earthRadius = 6367000; //approximate radius of earth in meters

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        $distance =  round($calculatedDistance);
        return $distance;
    }

    /**
     * 图片转化
     */
    public static function getRootImg($url){
        app()->configure('ppurl');
        $img_url = config('ppurl.img_url');
        return str_replace($img_url,"",$url);
    }

    /**
     * 获取完整图片
     */
    public static function  getUrlImg($url){
        app()->configure('ppurl');
        $img_url = config('ppurl.img_url');
        $url = str_replace($img_url,"",$url);
        return $img_url.$url;
    }

    /**
     * 获取时间
     * 传入 秒
     */
    public static  function getDesTime($time){
        if($time<=60){
            return $time."秒";
        }elseif($time<=3600){
            return ceil($time/60)."分钟";
        }else{
            return ceil($time/3600)."小时";
        }
    }

    /**
     * 通过经纬度 查询所在城市
     */
    public static  function getCityByLatLon($lat,$lon){
        $data = file_get_contents("http://api.map.baidu.com/geocoder?location=".$lat.",".$lon."&output=json&key=28bcdd84fae25699606ffad27f8da77b");
        $data = json_decode($data,true);
        return $data["result"]["addressComponent"]["city"];
    }

    /**
     * 根据经纬度获取所在区域信息
     */
    public static  function getAddressByLatLon($lat,$lon){
        $data = file_get_contents("http://api.map.baidu.com/geocoder?location=".$lat.",".$lon."&output=json&key=28bcdd84fae25699606ffad27f8da77b");
        $data = json_decode($data,true);
        return $data["result"]["addressComponent"];
    }

    /**
     * 上传
     */
    public static  function uploadFile($type,$folder,$base_string){
        if(empty($type)){
            return false;
        }
        $result = false;
        $return_path = false;
        $filename = "";
        $path_url =  dirname(dirname(dirname(__FILE__)))."/public/".$folder;
        switch($type){
            case 'picture':
                $picture_img = base64_decode($base_string);
                $img = imagecreatefromstring($picture_img);
                $filename = date('YmdHis').rand(1000,9999).".jpeg";
                $result = imagejpeg($img,$path_url."/".$filename);
                imagedestroy($img);

                break;
            case 'voice':
                $filename = date('YmdHis').rand(1000,9999).".mp3";
                $result = file_put_contents($path_url."/".$filename,$base_string);
                break;
            case 'video':
                $filename = date('YmdHis').rand(1000,9999).".mp4";
                $result = file_put_contents($path_url."/".$filename,$base_string);
                break;
        }
        if($result && !empty($filename)){
            $return_path = "/".$folder."/".$filename;
        }
        return $return_path;
    }

    /**
     * 获取首字母
     */
    public static  function getFirstChar($s0){
        $firstchar_ord=ord(strtoupper($s0{0}));
        if (($firstchar_ord>=65 and $firstchar_ord<=91)or($firstchar_ord>=48 and $firstchar_ord<=57)) return $s0{0};
        $s=iconv("UTF-8","gb2312", $s0);
        $asc=ord($s{0})*256+ord($s{1})-65536;
        if($asc>=-20319 and $asc<=-20284)return "A";
        if($asc>=-20283 and $asc<=-19776)return "B";
        if($asc>=-19775 and $asc<=-19219)return "C";
        if($asc>=-19218 and $asc<=-18711)return "D";
        if($asc>=-18710 and $asc<=-18527)return "E";
        if($asc>=-18526 and $asc<=-18240)return "F";
        if($asc>=-18239 and $asc<=-17923)return "G";
        if($asc>=-17922 and $asc<=-17418)return "H";
        if($asc>=-17417 and $asc<=-16475)return "J";
        if($asc>=-16474 and $asc<=-16213)return "K";
        if($asc>=-16212 and $asc<=-15641)return "L";
        if($asc>=-15640 and $asc<=-15166)return "M";
        if($asc>=-15165 and $asc<=-14923)return "N";
        if($asc>=-14922 and $asc<=-14915)return "O";
        if($asc>=-14914 and $asc<=-14631)return "P";
        if($asc>=-14630 and $asc<=-14150)return "Q";
        if($asc>=-14149 and $asc<=-14091)return "R";
        if($asc>=-14090 and $asc<=-13319)return "S";
        if($asc>=-13318 and $asc<=-12839)return "T";
        if($asc>=-12838 and $asc<=-12557)return "W";
        if($asc>=-12556 and $asc<=-11848)return "X";
        if($asc>=-11847 and $asc<=-11056)return "Y";
        if($asc>=-11055 and $asc<=-10247)return "Z";
        return 'other';

    }

    /**
     * 推送
     */
    public static function sendPush($data,$type = 1){
        app()->configure('ppurl');
        $img_url = config('ppurl.img_url');
        $query = '1=1';
        if(empty($data["message"])){
            $data["message"] = "凹凸圈";
        }
        foreach ($data as $name => $value) {
            $query.= '&'.$name.'='.$value;
        }
        $url = $img_url.'/api/message/system_push?type='.$type."&".$query;
        $return_content = SELF::_post_url_post_data($url);
        $return_arr = json_decode($return_content,true);
        if ($return_arr && $return_arr['status'] == 1) {
            return true;
        }else{
            return false;
        }
    }

    public static function _post_url_post_data($url,$push_data = array()){
        $app_token = "apptest";
        $random_str = time();
        $sign = md5(md5(md5($app_token.$random_str)));

        $apptype = "android";
        $appversion = "1.0.0";
        $data = array(
            'sign'=>$sign,
            'random_str'=>$random_str,
            'apptype'=>$apptype,
            'appversion'=>$appversion,
        );
        $data = array_merge($data,$push_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}